﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using OxyPlot;
using RunningWavelet.DataGenerators;
using RunningWavelet.Properties;
using RunningWavelet.WaveletController;

namespace RunningWavelet
{
    public partial class Form1 : Form, IUserFields
    {
        private RunningWaveletController _controller;

        public Form1()
        {
            InitializeComponent();
            Closed += (sender, args) => _controller.StopGenerator();
            toolStripSplitButton1.DropDownItems.AddRange(GetWaveletDecompositionNumber);

            if (_controller != null && (_controller.Generator as WagoGenerator) != null)
            {
                RegisterWagoEvents((WagoGenerator)_controller.Generator);
            }

            ucSettingsPannel1.ApplySettingsEvent += (sender, args) =>
            {
                //Скрытие бового меню
                toolStripButton4_Click(sender, args);
                //Сохранение настроек подключения
                SaveConnectionSettings();
                //Пересоздание подключения с новыми параметрами
                _controller.ReInitializeGenerator(GeneratorName);
            };
        }

        private void RegisterWagoEvents(WagoGenerator wg)
        {
            ucSettingsPannel1.WagoConnectEvent += (sender, args) =>
            {
                SaveConnectionSettings();
                if (wg.WagoConnect())
                    MessageBox.Show(string.Format("Подключение по ModBus установлено с IP ({0}:{1})",
                            ConnectionSettings.WagoAddressIp, ConnectionSettings.WagoPort),
                        "Подключение установлено!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            };
            ucSettingsPannel1.WagoDisconnectEvent += (sender, args) => wg.WagoDisconnect();
            ucSettingsPannel1.WagoCheckRegisters += (sender, args) =>
            {
                var rgs = wg.CheckRegisters(ConnectionSettings.WagoRegisterStart,
                    ConnectionSettings.WagoRegisterCount);
                if (rgs != null)
                {
                    MessageBox.Show(rgs.ToList().Select(x => x.ToString()).Aggregate((i, j) => i + ',' + j));
                }
            };
        }

        public ToolStripItem[] GetWaveletDecompositionNumber
        {
            get
            {
                //return ToolStripMenuItem

                var a = new ToolStripItem[WaveletSettings.DecompilationDepth];


                for (var i = 0; i < WaveletSettings.DecompilationDepth; i++)
                {
                    a[i] = new ToolStripMenuItem
                    {
                        Name = "Level_" + i,
                        Text = "Уровень " + (i + 1)
                    };
                    a[i].Click += (sender, e) => _controller.ChangeChartView(i);
                }
                return a;
            }
        }

        public IEnumerable<DataPoint> Chart2Data
        {
            get
            {
                return (IEnumerable<DataPoint>)plotView2.GetOrCreateSeries(1).ItemsSource;
            }
            set
            {
                plotView2.UpdateSerie(1, value);
                plotView2.PlotRefresh();
            }
        }

        public string GeneratorName
        {
            get { return (string) toolStripComboBox1.SelectedItem; }
            set { toolStripComboBox1.Text = value; }
        }

        public string StatusString
        {
            get { return toolStripStatusLabel1.Text; }
            set { toolStripStatusLabel1.Text = value; }
        }

        public void SetController(RunningWaveletController controller)
        {
            _controller = controller;
        }

        public IConnetionSettings ConnectionSettings
        {
            get { return ucSettingsPannel1; }
            set { throw new NotImplementedException(); }
        }

        public IWaveletSettings WaveletSettings
        {
            get { return ucSettingsPannel1; }
            set { throw new NotImplementedException(); }
        }

        public IEnumerable<DataPoint> Chart1Data
        {
            get
            {
                return (IEnumerable<DataPoint>)plotView1.GetOrCreateSeries(1).ItemsSource;
            }
            set
            {
                plotView1.UpdateSerie(1, value);
                plotView1.PlotRefresh();
            }
        }

        //start button
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            _controller.StartGenerator();
        }

        //pause button
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            _controller.StopGenerator();
        }

        public void SaveConnectionSettings()
        {
            Settings.Default.Save();
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            _controller.StartGenerator();
        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            _controller.StopGenerator();
        }

        private void tbWLevel_Enter(object sender, EventArgs e)
        {
            _controller.UpdateWaveletSettings();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            ucSettingsPannel1.Visible = ucSettingsPannel1.Visible != true;
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var gn = sender as ToolStripComboBox;
            if (gn != null) _controller.ReInitializeGenerator(gn.SelectedItem.ToString());
        }
    }
}